package cn.mrlong.base.permission

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity


/**
 * 作者：BINGO
 * 时间：2021/04/07 16:46
 * 权限请求控制
 * 1、扩展activity
 * 2、传入context,请求
 */
object PermissionUtils {
    final const val TAG = "PermissionUtils.TAG"
    fun requestPermissions(
        activity: FragmentActivity,
        vararg permissions: String,
        callback: PermissionCallback
    ) {
        val fragmentManager = activity.supportFragmentManager
        val existedFragment = fragmentManager.findFragmentByTag(TAG)
        val fragment = if (existedFragment != null) {
            existedFragment as PermissionFragment
        } else {
            val invisibleFragment = PermissionFragment()
            fragmentManager.beginTransaction().add(invisibleFragment, TAG).commitNow()
            invisibleFragment
        }
        fragment.requestRunPermissions(callback, *permissions)
    }
}

/**
 * 扩展方式 FragmentActivity添加权限请求
 * @receiver FragmentActivity
 * @param permissions Array<out String>
 * @param callback Function2<[@kotlin.ParameterName] Boolean,
 *                           [@kotlin.ParameterName] List<String>, Unit>
 */
inline fun FragmentActivity.reqPermission(
    vararg permissions: String,
    noinline callback: PermissionCallback
) {
    val fragmentManager = this.supportFragmentManager
    val existedFragment = fragmentManager.findFragmentByTag(PermissionUtils.TAG)
    val fragment = if (existedFragment != null) {
        existedFragment as PermissionFragment
    } else {
        val invisibleFragment = PermissionFragment()
        fragmentManager.beginTransaction().add(invisibleFragment, PermissionUtils.TAG).commitNow()
        invisibleFragment
    }
    fragment.requestRunPermissions(callback, *permissions)
}

/**
 * 扩展方式 Fragment添加权限请求
 * @receiver Fragment
 * @param permissions Array<out String>
 * @param callback Function2<[@kotlin.ParameterName] Boolean,
 *                           [@kotlin.ParameterName] List<String>, Unit>
 */
inline fun Fragment.reqPermission(
    vararg permissions: String,
    noinline callback: PermissionCallback
) {

    if (null != this.activity) {
        val fragmentManager = this.requireActivity().supportFragmentManager
        val existedFragment = fragmentManager.findFragmentByTag(PermissionUtils.TAG)
        val fragment = if (existedFragment != null) {
            existedFragment as PermissionFragment
        } else {
            val invisibleFragment = PermissionFragment()
            fragmentManager.beginTransaction().add(invisibleFragment, PermissionUtils.TAG)
                .commitNow()
            invisibleFragment
        }
        fragment.requestRunPermissions(callback, *permissions)
    } else {
        throw Exception("get context err")
    }
}